<template>
  <div class="app-container">
    <el-form>
      <el-form-item label="请输入iccid起止号段" prop="status" label-width="150px">
  <span
    class="el-form-item__label"
    style="font-weight: 700; display: block; margin-bottom: 8px;"
  >
  </span>
        <div style="display: flex; justify-content: space-between; align-items: center; gap: 10px;">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-input
              v-model="queryParams.startNo"
              placeholder="开始号段"
              clearable
              size="small"
              style="width: 200px"
              @keyup.enter.native="handleQuery"
            />
            <span>至</span>
            <el-input
              v-model="queryParams.endNo"
              placeholder="结束号段"
              clearable
              size="small"
              style="width: 200px"
              @keyup.enter.native="handleQuery"
            />

            <el-form :model="queryParams" :rules="rules" label-width="100px">
              <el-form-item label="查询年限" prop="type">
                <el-select
                  v-model="queryParams.type"
                  placeholder="请选择查询年限"
                  size="small"
                  style="width: 150px"
                  clearable
                >
                  <el-option label="2025年" value="2025"></el-option>
                  <el-option label="2024年" value="2024"></el-option>
<!--                  <el-option label="移动" value="mobile"></el-option>
                  <el-option label="电信5G" value="telecom"></el-option>-->
                </el-select>
              </el-form-item>
            </el-form>
            <el-button type="primary" size="small" @click="getList">查询</el-button>
<!--            <el-button type="primary" size="small" @click="syncUpstreamData">同步上游数据</el-button>-->
          </div>
          <!-- 右侧：按钮组 -->
          <div style="display: flex; gap: 20px;">
            <el-button type="success" size="small" @click="exportData">导出</el-button>
          </div>
        </div>
      </el-form-item>

    </el-form>
    <div style="height: 8px"></div>
    <!-- 添加间距 -->
    <el-table :data="tableData" ref="multipleTable" tooltip-effect="dark" style="width: 100%"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="msisdn" width="150" prop="msisdn" align="center"/>
      <el-table-column label="iccid" width="200" prop="iccid" align="center"/>
      <el-table-column label="imsi" width="180" prop="imsi" align="center"/>
      <el-table-column
        label="卡状态"
        key="status_ShowId"
        prop="status_ShowId"
        width="100"
      >
        <template slot-scope="scope">
          {{ tools.getDkeyValue(stateShowId, scope.row.status_ShowId) }}
        </template>
      </el-table-column>
      <el-table-column label="1月" prop="one_flow" align="center"/>
      <el-table-column label="2月" prop="two_flow" align="center"/>
      <el-table-column label="3月" prop="three_flow" align="center"/>
      <el-table-column label="4月" prop="four_flow" align="center"/>
      <el-table-column label="5月" prop="five_flow" align="center"/>
      <el-table-column label="6月" prop="six_flow" align="center"/>
      <el-table-column label="7月" prop="seven_flow" align="center"/>
      <el-table-column label="8月" prop="eight_flow" align="center"/>
      <el-table-column label="9月" prop="nine_flow" align="center"/>
      <el-table-column label="10月" prop="ten_flow" align="center"/>
      <el-table-column label="11月" prop="eleven_flow" align="center"/>
      <el-table-column label="12月" prop="twelve_flow" align="center"/>
<!--      <el-table-column label="同步日期" prop="synTime" align="center"/>-->
<!--      <el-table-column label="是否同步" prop="is_syn" align="center"/>-->
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>
<script>
import tools from '@/utils/yunze/tools'

import {
  exportMonthDataOfYear,
  findDeptUser, getMonthListOf2025,
  syncUpstreamData
} from '../../../../api/yunze/flowcard/card/card'
import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getToken } from '@/utils/auth'

export default {
  name: 'index',
  components: { Treeselect },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  data() {
    return {
      openCardSel: false,
      form: {},
      importLoading: false,
      isLoading: false,
      title: '',
      filterText: '',
      tools: tools,
      userArr: [],//企业下用户数组
      selectTotal: '',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 选中数组
      ids: '',
      // 部门树选项
      deptOptions: undefined,
      tableData: [],
      // 遮罩层
      loading: true,
      open: false,
      total: 0,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      upload: {
        Pstr: '',//携带参数
        // 是否显示弹出层（导入）
        open: false,
        Number: false,
        // 弹出层标题（导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        // otherUrl: process.env.VUE_APP_BASE_API + '/yunze/card/batchQueryCardList'
        otherUrl: process.env.VUE_APP_BASE_API + '/yunze/card/importModuleInfo'
      },
      updatel: {
        title: '',
        Number: false
      },
      multipleSelection: [],
      deptId: undefined,
      deptIdItem: undefined,
      // stateShowId: undefined,
      DeptOptions: [],
      deptName: undefined,
      visable: false,
      rules: {
        type: [
          { required: true, message: '请选择卡类型', trigger: 'change' }
        ]
      },
      // 卡状态描述 字典
      stateOptions: [
        {
          dictLabel: ''
        }
      ],

      stateShowId: [], // 卡状态

      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startNo: '',
        type: '',// 用于绑定下拉框选中的值
        endNo: '',
        cardValue: ''
      }
    }
  },
  created() {
    this.getList()
    if (window['DeptOptions'] != undefined && window['DeptOptions'] != null && window['DeptOptions'] != '') {
      this.DeptOptions = window['DeptOptions']
    } else {
      this.getDeptName().then(response => {
        let jsonobj = JSON.parse(tools.Decrypt(response))
        window['DeptOptions'] = jsonobj.Data
        this.DeptOptions = window['DeptOptions']
      })
    }
    //加载 卡状态
    if (
      window['stateShowId'] != undefined &&
      window['stateShowId'] != null &&
      window['stateShowId'] != ''
    ) {
      this.stateShowId = window['stateShowId']
    } else {
      this.getDicts('yunze_card_status_ShowId').then((response) => {
        window['stateShowId'] = response.data
        this.stateShowId = window['stateShowId']
      })
    }
  },
  methods: {
    // 验证是否选择了卡类型
    validateSelection() {
      if (!this.queryParams.type) {
        this.$message.error('请先选择卡类型')
        return false
      }
      return true
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.importLoading = true
      this.submitFileFormBtn = false
      this.$refs.upload.submit()
      setTimeout(() => {
        this.importLoading = false
        this.getList()
        // 这里可以放置你想要延迟执行的代码
      }, 3000)
    },

    importModule() {
      this.downloadConversion('/getcsv/importModule.xlsx')
    },

    downloadConversion(path) {
      let map = {}
      map.path = path
      map.token = getToken()
      let Pwd_Str = tools.encrypt(JSON.stringify(map))
      window.open(
        process.env.VUE_APP_BASE_API +
        '/yunze/ExecutionTask/downloadConversion?Pstr=' +
        Pwd_Str,
        '_blank'
      )
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.updatel.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      let jsonobj = JSON.parse(tools.Decrypt(response.msg))
      if (response.code == 200) {
        this.tableData = jsonobj.Data
        // console.log('拿到的数据为：=========' + this.tableData)
        this.total = jsonobj.Pu.rowCount
      } else {
        this.msgError(jsonobj.msg)
      }
      this.upload.open = false
      this.openCardSel = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
    },

    //同步数据
    syncUpstreamData() {
      if (!this.validateSelection()) return
      this.$message.info('后台正在同步数据请稍后...')
      let Pwd_Str = tools.encrypt(JSON.stringify(this.queryParams))
      syncUpstreamData(Pwd_Str)
    },

    //导出数据
    exportData() {
      if (!this.validateSelection()) return
      let Pwd_Str = tools.encrypt(JSON.stringify(this.queryParams))
      exportMonthDataOfYear(Pwd_Str).then((response) => {
        // 请求成功返回后，获取到Excel文件的二进制数据
        const blob = new Blob([response], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        // 创建下载链接
        const downloadUrl = URL.createObjectURL(blob)
        // 创建一个隐藏的a标签，设置下载链接和文件名
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = downloadUrl
        link.download = '月流量报表导出.xlsx'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.loading = false
        alert('导出成功，请在下载文件中查看')
      })
        .catch((error) => {
          // 请求失败处理
          console.error(error)
        })
    },
    //获取条件查询数据
    getList() {
      this.loading = true
      let Pwd_Str = tools.encrypt(JSON.stringify(this.queryParams))
      getMonthListOf2025(Pwd_Str).then(res => {
        let decrypted = tools.Decrypt(res)
        if (typeof decrypted === 'object') {
          this.tableData = decrypted.Data
          this.total = decrypted.Pu.rowCount
        } else if (typeof decrypted === 'string') {
          try {
            let jsonobj = JSON.parse(decrypted)
            this.tableData = jsonobj.Data.Data
            this.total = jsonobj.Data.Pu.rowCount
          } catch (error) {
            console.error('JSON 解析失败:', error)
          }
        }
        this.loading = false
      }).catch(error => {
        console.error('请求失败:', error)
        this.loading = false
      })
    },

    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleCheckChange(data) {
      if (this.currentNodeKey?.id && this.$refs.tree) {
        this.$refs.tree.setCheckedKeys([])
        // 更新当前选中节点的 key
        this.$refs.tree.setCheckedNodes([data])
      }
      // 更新当前选中节点的 key
      this.currentNodeKey = data
      let putDate = { dept_id: undefined }
      putDate.dept_id = this.currentNodeKey.id
      this.deptId = putDate.dept_id
      let Pwd_Str = tools.encrypt(JSON.stringify(putDate))
      findDeptUser(Pwd_Str).then(res => {
        let reData = JSON.parse(tools.Decrypt(res)).Data
        this.userArr = reData
      })
    },
    querSearch() {
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id).join(',')
      this.selectTotal = selection.length
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 查询企业下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data
      })
    },
    cancel() {

      this.visable = false
    },
    restQuery() {
      this.queryParams = {
        startNo: '',
        endNo: '',
        cardValue: ''
      }
      this.getList()
    },
    SynAllCardSel() {
      this.openCardSel = true
    },
    openChange() {
      this.deptOptions = []
      this.queryParams = {}
      this.userArr = []
      if (this.ids == '') {
        this.$message.warning('请先勾选卡信息 !')
      } else {
        this.visable = true
        this.title = '卡划拨'
        this.getTreeselect()
      }

    }
  }
}
</script>
<style scoped>

</style>
